﻿using Sustainalytics.Accounts.BusinessLogic;
using Sustainalytics.OAuth.Services.Common;
using Sustainalytics.Utils.Logging.Serilog;
using Sustainalytics.Utils.Logging.Serilog.Messages;
using Sustainalytics.Utils.Serilog;
using System;
using System.Configuration;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Web.Http.Cors;

namespace Sustainalytics.Accounts.Service.Controllers
{
    [EnableCors(origins: "*", headers: "*", methods: "*")]
    public class IpLoginController : ApiController
    {
        private readonly IIpDataCheck _checker;

        public IpLoginController(IIpDataCheck checker)
        {
            _checker = checker;
        }

        [Route("api/account/iplogin")]
        public HttpResponseMessage Post()
        {
            try
            {
                var getIpRequest = Request.GetOwinContext().Request.RemoteIpAddress;
                var findAccount = _checker.GetAccountFromIp(getIpRequest);
                var userData = new
                {
                    findAccount.UserName,
                    UserPassword = AuthOperations.AuthOperations.DEFAULT_IP_LOGIN_PASSWORD
                };
                var tokenData =
                    string.Format(
                        "grant_type=password&username={0}&password={1}&client_id=clientId1&client_secret=secret1",
                        userData.UserName, userData.UserPassword);
                var url = ConfigurationManager.AppSettings["AccessTokenUrl"];
                Console.WriteLine(url);
                Console.WriteLine(tokenData);

                ServicePointManager.ServerCertificateValidationCallback = (sender, certificate, chain, errors) => true;
                using (var httpclient = new HttpClient(new HttpClientHandler() { ClientCertificateOptions = ClientCertificateOption.Automatic }))
                {
                    var data = httpclient.PostAsync(url, new StringContent(tokenData)).Result;
                    if (data.IsSuccessStatusCode)
                    {
                        CommonEventSerilog.Log.Info(AuthServiceMessage.SuceesfulIpLogin, getIpRequest, findAccount);
                    }
                    else
                    {
                        var allData = data.Content.ReadAsStringAsync().Result;
                        CommonEventSerilog.Log.CallerError(AuthServiceMessage.FailureIpLogin, DebugHelper.GetCallerInfo(), getIpRequest, findAccount, allData);
                    }

                    data.Headers.Add("Username", userData.UserName);
                    return data;
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
                CommonEventSerilog.Log.CallerError(AuthServiceMessage.ExceptionIpLogin, DebugHelper.GetCallerInfo(), ex.ToString());
                return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, ex.ToString());
            }
        }
    }
}
